package com.pingan.mybatis.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;



/**
 * @AUTHOR:LIUCHAO;
 * @DATE: 2020/11/26 17:46
 */
public class DESUtil {

    /** 日志记录对象 */
    private static final Logger LOGGER = LoggerFactory.getLogger(DESUtil.class);

    private static Key key;

    /** 密钥 */
    private static String SECRET_KEY = "secretKey";

    /** 必须设置编码 */
    private static String CHARSET = "UTF-8";

    /** 算法常量,这里使用DES */
    private static String ALGORITHM = "DES";

    static {
        try {
            // 生成DES算法对象
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            // 运用SHA1安全策略
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // 设置密钥
            secureRandom.setSeed(SECRET_KEY.getBytes());
            // 初始化
            generator.init(secureRandom);
            // 生成密钥对象
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            LOGGER.error("生成密钥对象失败！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     *
     * @param str
     * @return
     */
    public static String getEncryptString(String str) {
        Base64 base64 = new Base64();
        try {
            byte[] bytes = str.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(base64.encode(doFinal));
        } catch (Exception e) {
            LOGGER.error("加密失败！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String getDecryptString(String str) {
        Base64 base64 = new Base64();
        try {
            byte[] bytes = base64.decode(str);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSET);
        } catch (Exception e) {
            LOGGER.error("解密失败！");
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 加密测试
        System.out.println(getEncryptString("root"));
        System.out.println(getEncryptString("123456"));

        // 解密测试
        System.out.println(getDecryptString("G5diwzl9+NY="));
        System.out.println(getDecryptString("DF29YY/dEVQ="));
    }
}
